<?php

namespace backend\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use common\models\Settings;

/**
 * SettingsSearch represents the model behind the search form about `common\models\Settings`.
 */
class SettingsSearch extends Settings
{
    public $created_at_start;
    public $created_at_end;

    /**
    * @inheritdoc
    */
    public function attributeLabels()
    {
      return array_merge(
        parent::attributeLabels(),
        [
        'created_at_start' => '开始时间',
        'created_at_end' => '结束时间',
        ]
      );
    }
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id', 'created_at', 'updated_at', 'deleted'], 'integer'],
            [['option_name', 'option_key', 'option_val'], 'safe'],
            [['created_at_start','created_at_end'], 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
    * @param array() $params
    * @param int $pageSize
    * @param int $f 0|1
    * @return ActiveDataProvider
    */
    public function search($params,$pageSize = 20,$f = 0)
    {
        $query = Settings::find($f);

        // add conditions that should always apply here

        $dataProvider = new ActiveDataProvider([
            'query' => &$query,
            'pagination' => ['pageSize'=>$pageSize],
            'sort'=>[
                'defaultOrder'=>[
                    'id'=> SORT_DESC,
                ],
            ],
        ]);

        $this->load($params);

        if (!$this->validate()) {
            return $dataProvider;
        }

        // grid filtering conditions
        $query->andFilterWhere([
            'id' => $this->id,
            'created_at' => $this->created_at,
            'updated_at' => $this->updated_at,
            'deleted' => $this->deleted,
        ]);

        $query->andFilterWhere(['like', 'option_name', $this->option_name])
            ->andFilterWhere(['like', 'option_key', $this->option_key])
            ->andFilterWhere(['like', 'option_val', $this->option_val]);

        if(!empty($this->created_at_start) && !empty($this->created_at_end)){
          $query->andFilterWhere(['between', $this->a.'.created_at', strtotime($this->created_at_start),strtotime($this->created_at_end)]);
        }


        return $dataProvider;
    }
}
